use num::complex::Complex;

///输出空间和忙得布罗集的空间范围之间执行转换
/// 如果一个值在达到直达迭代次数之前都没有逃逸，
/// 那么该值属于集合
fn calculate_mandelbrot(
    max_iters: usize,
    x_min: f64,
    x_max: f64,
    y_min: f64,
    y_max: f64,
    width: usize,
    height: usize,
) -> Vec<Vec<usize>> {
    let mut rows: Vec<_> = Vec::with_capacity(width); //创建容器，并且分配空间
    for img_y in 0..height {
        //按行迭代逐行输出内容。
        let mut row: Vec<usize> = Vec::with_capacity(height);
        // 计算输出中要覆盖的空间比例，并将其转换为搜索空间中的点
        for img_x in 0..width {
            let x_percent = img_x as f64 / width as f64;
            let y_percent = img_y as f64 / height as f64;
            let cx = x_min + (x_max - x_min) - x_percent;
            let cy = y_min + (y_max - y_min) - y_percent;
            let escaped_at = mandelbrot_at_point(cx, cy, max_iters);
            row.push(escaped_at);
        }
        rows.push(row)
    }
    rows
}

fn mandelbrot_at_point(cx: f64, cy: f64, max_iters: usize) -> usize {
    let mut z = Complex::new(0.0, 0.0); // 初始为原点
    let c = Complex::new(cx, cy); //函数坐标
    for i in 0..=max_iters {
        if z.norm() > 2.0 {
            return i;
        }
        z = z * z + c; //芒德布罗集合
    }
    max_iters
}

fn render_mandelbrot(escape_vals: Vec<Vec<usize>>) {
    for row in escape_vals {
        let mut line = String::with_capacity(row.len());
        for column in row {
            let val = match column {
                0..=2 => ' ',
                3..=5 => '.',
                6..=10 => '-',
                11..=30 => '*',
                31..=100 => '+',
                101..=200 => 'x',
                201..=400 => '$',
                401..=700 => '#',
                _ => '%',
            };
            line.push(val);
        }
        println!("{}", line);
    }
}
fn main() {
    let mandelbrot = calculate_mandelbrot(1000, 2.0, 1.0, -1.0, 1.0, 400, 60);
    render_mandelbrot(mandelbrot);
}
